//
//  QuickEditRemarkView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 10.05.25.
//

import SwiftUI

struct QuickEditRemarkView: View {
    
    @Environment(\.presentToast) var presentToast
    
    @Environment(\.presentationMode) var presentationMode;
    
    @StateObject var viewModel: QuickEditRemarkViewModel
    
    @State var remark: String = ""
    
    @FocusState var isRemarkFocus: Bool

    
    init(detail: AccountingDetailCombine) {
        self._viewModel = StateObject(wrappedValue: QuickEditRemarkViewModel(detail: detail))
    }
    
    var body: some View {
        HStack {
            CategoryIconView(item: viewModel.detail.category)
            TextField(viewModel.detail.getCategoryName(), text: $remark)
                .font(.system(size: 15))
                .foregroundColor(Color.koiColorTitle)
                .focused($isRemarkFocus)
                .submitLabel(.done)
                .onSubmit {
                    viewModel.updateRemark(remark)
                }
            Spacer()
            Button(action: {
                viewModel.updateRemark(remark)
            }) {
                Text("完成")
                    .font(.system(size: 14))
                    .foregroundColor(Color.white)
                    .fontWeight(.medium)
                    .padding(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 16))
                    .background(Color.koiColorPrimary)
                    .cornerRadius(16)
            }
        }
        .padding(EdgeInsets(top: 2, leading: 16, bottom: 2, trailing: 16))
        .onChange(of: viewModel.updateState) { value in
            if value == "" {
                return
            }
            if value == "success" {
                presentToast(.init(message: "修改成功"))
                KoiEvent.homeReload.send()
                presentationMode.wrappedValue.dismiss()
            } else {
                presentToast(.init(message: value))
            }
        }
        .onAppear {
            remark = viewModel.detail.detail.remark ?? ""
            isRemarkFocus = true
        }
    }
}

#Preview {
    QuickEditRemarkView(detail: AccountingDetailCombine.previewData())
}
